package com.water.smartfarm.register;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.water.smartfarm.R;
import com.water.smartfarm.tools.Const;
import com.water.smartfarm.tools.DBHelper;

import java.text.SimpleDateFormat;
import java.util.Date;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
    DBHelper dbHelper;
    SQLiteDatabase db;
    private TextView userText;
    private EditText userInput;
    private EditText passInput;
    private Button registerBtn;

    String user;
    String pass;
    String time;


    private void initView() {
        userText = (TextView) findViewById(R.id.user_text);
        userInput = (EditText) findViewById(R.id.user_input);
        passInput = (EditText) findViewById(R.id.pass_input);
        registerBtn = (Button) findViewById(R.id.register_btn);
        registerBtn.setOnClickListener(this);
        dbHelper = new DBHelper(this, Const.USER);
        db = dbHelper.getWritableDatabase();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.register_btn:
                initRegister();
                Toast.makeText(getApplicationContext(), "注册成功",
                        Toast.LENGTH_SHORT).show();
                finish();
                break;

        }
    }

    private void initRegister() {
        user = userInput.getText().toString().trim();
        pass = passInput.getText().toString().trim();
        time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
//        String sql = "insert into USER (name,pass,time) values ('"+user+"','"+pass+"','"+time+"')";
        ContentValues values = new ContentValues();
        values.put("name", user);
        values.put("pass", pass);
        values.put("time", time);
        //调用方法插入数据
        db.insert(Const.USER, "id", values);
        values.clear();
        db.close();
    }
}
